package com.zzyl.nursing.service.impl;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.util.CacheConstants;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 设备管理Service业务层处理
 *
 * @author 小新IP归属中国
 * @date 2025-06-28
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties configProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }


    /**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void syncProductList() throws Exception {
        QueryProductListRequest queryProductListRequest = new QueryProductListRequest();

        queryProductListRequest.setCurrentPage(1);
        queryProductListRequest.setPageSize(2000);
        queryProductListRequest.setIotInstanceId(configProperties.getIotInstanceId());


        QueryProductListResponse response = client.queryProductList(queryProductListRequest);

        if (!response.getBody().success) {
            throw new BaseException("同步产品数据失败!");
        }

        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, JSONUtil.toJsonStr(response.getBody().getData().getList().getProductInfo()));
    }

    @Override
    public List<ProductVo> allProduct() {
        String jsonStr = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        if (StrUtil.isEmpty(jsonStr)) {
            return null;
        }
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(DeviceDto dto) {

        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if (count != 0) throw new BaseException("设备名称已存在，请重新输入");
        RegisterDeviceResponse response;
        try {
            response = client.registerDevice(dto.getRegisterDeviceRequest());
        } catch (Exception e) {
            throw new BaseException("注册设备，调用失败");
        }

        if (!response.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }

        QueryProductResponse queryProductResponse;
        QueryProductRequest queryProductRequest = new QueryProductRequest();
        queryProductRequest.setProductKey(dto.getProductKey());
        queryProductRequest.setIotInstanceId(configProperties.getIotInstanceId());
        try {
            queryProductResponse = client.queryProduct(queryProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品，调用失败");
        }

        if (!queryProductResponse.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }

        Device device = BeanUtil.toBean(dto, Device.class);

        if (device.getLocationType().equals(0)) {
            device.setPhysicalLocationType(-1);
        }

        device.setIotId(response.getBody().getData().getIotId());


        try {
            deviceMapper.insertDevice(device);
        } catch (Exception e) {

            //删除iot中的设备
            DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
            deleteDeviceRequest.setDeviceName(device.getDeviceName());
            deleteDeviceRequest.setProductKey(device.getProductKey());
            deleteDeviceRequest.setIotId(device.getIotId());
            deleteDeviceRequest.setIotInstanceId(configProperties.getIotInstanceId());
            try {
                client.deleteDevice(deleteDeviceRequest);
            } catch (Exception ex) {
                throw new BaseException(" 删除设备，调用失败");
            }
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }


    }

    @Override
    public DeviceVo queryDeviceDetail(DeviceDto dto) {
        QueryDeviceDetailRequest queryDeviceDetailRequest = new QueryDeviceDetailRequest();
        queryDeviceDetailRequest.setIotId(dto.getIotId());
        QueryDeviceDetailResponse response;
        queryDeviceDetailRequest.setProductKey(dto.getProductKey());
        try {
            response = client.queryDeviceDetail(queryDeviceDetailRequest);
        } catch (Exception e) {
            throw new BaseException("查询设备详细数据失败");
        }

        if (!response.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }

        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, dto.getIotId()));
        DeviceVo deviceVo = BeanUtil.copyProperties(device, DeviceVo.class);

        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = response.getBody().getData();
        BeanUtil.copyProperties(deviceVo, data, CopyOptions.create().ignoreNullValue());
        return deviceVo;
    }

    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotId(configProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse queryDevicePropertyStatusResponse;

        try {
            queryDevicePropertyStatusResponse = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("查询指定设备的物模型运行状态失败");
        }

        if (!queryDevicePropertyStatusResponse.getBody().success) {
            throw new BaseException(queryDevicePropertyStatusResponse.getBody().getErrorMessage());
        }


        return AjaxResult.success(queryDevicePropertyStatusResponse.getBody().getData());
    }

    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(configProperties.getIotInstanceId());

        QueryThingModelPublishedResponse queryThingModelPublishedResponse;
        try {
            queryThingModelPublishedResponse = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("查看指定产品的已发布物模型中的功能定义详情失败");
        }

        if (!queryThingModelPublishedResponse.getBody().success) {
            throw new BaseException(queryThingModelPublishedResponse.getBody().getErrorMessage());
        }
        return AjaxResult.success(queryThingModelPublishedResponse.getBody().getData());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult deleteDevice(DeviceDto dto) {

        int delete = deviceMapper.delete(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, dto.getIotId()).eq(Device::getProductKey, dto.getProductKey()));
        if (delete == 0) throw new BaseException("本地删除设备失败");

        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setIotId(dto.getIotId());
        request.setProductKey(dto.getProductKey());
        request.setIotInstanceId(configProperties.getIotInstanceId());
        DeleteDeviceResponse response;
        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("远程删除设备失败");
        }

        if (!response.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }

        return AjaxResult.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateDevice(DeviceDto dto) {
        Device device = BeanUtil.copyProperties(dto, Device.class);
        if (device.getLocationType() == 0) {
            device.setPhysicalLocationType(-1);
        }
        boolean i = updateById(device);
        if (!i) throw new BaseException("本地修改设备失败");

        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();
        request.setIotInstanceId(configProperties.getIotInstanceId());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> list = new ArrayList<>();
        list.add(new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo().setDeviceName(dto.getDeviceName()).setNickname(dto.getNickname()).setIotId(dto.getIotId()).setProductKey(dto.getProductKey()));
        request.setDeviceNicknameInfo(list);
        BatchUpdateDeviceNicknameResponse response;
        try {
            response = client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new BaseException("远程修改设备失败");
        }

        if (!response.getBody().success) {
            throw new BaseException(response.getBody().getErrorMessage());
        }


        return AjaxResult.success();
    }

}
